package com.ken.mqbase.ack;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

/**
 * 自定义消费失败处理类
 * Created by renchongyu on 2018/11/19.
 */
public class MyAckConsumer extends DefaultConsumer{

    private Channel channel;

    public MyAckConsumer(Channel channel) {
        super(channel);
        this.channel = channel;
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        System.out.println("body = "+ new String(body));

//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        Integer ref = (Integer) properties.getHeaders().get("num");
        if(ref!=null && ref == 0){
            channel.basicAck(envelope.getDeliveryTag(),false);
            //channel.basicNack(envelope.getDeliveryTag(),false,true);//失败重新放回队列
        }else {
            channel.basicAck(envelope.getDeliveryTag(),false);
        }
    }
}
